"""
用户相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.user import UserResponse, UserUpdate
from app.schemas.common import ApiResponse, SuccessResponse, PageData
from app.models.user import User

router = APIRouter()


@router.get("/search", response_model=ApiResponse[PageData[UserResponse]])
async def search_users(
    keyword: str = Query(..., description="搜索关键词"),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    搜索用户/球员
    支持按昵称、手机号模糊搜索
    """
    query = db.query(User).filter(
        (User.nick_name.like(f"%{keyword}%")) |
        (User.phone.like(f"%{keyword}%"))
    )
    
    # 分页
    total = query.count()
    users = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 转换为响应格式
    user_list = []
    for user in users:
        user_dict = user.to_dict()
        user_list.append(UserResponse(**user_dict))
    
    return ApiResponse(
        data=PageData(
            list=user_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/info", response_model=ApiResponse[UserResponse])
async def get_user_info(
    current_user: User = Depends(get_current_user)
):
    """获取当前用户信息"""
    return ApiResponse(
        data=UserResponse(**current_user.to_dict())
    )


@router.put("/update", response_model=ApiResponse[UserResponse])
async def update_user_info(
    user_data: UserUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户信息"""
    from app.models.team import TeamMember
    
    update_data = user_data.model_dump(exclude_unset=True)
    avatar_updated = False
    nickname_updated = False
    
    for field, value in update_data.items():
        # 转换驼峰命名为下划线命名
        db_field = field
        if field == "nickName":
            db_field = "nick_name"
            nickname_updated = True
        elif field == "cityId":
            db_field = "city_id"
        elif field == "cityName":
            db_field = "city_name"
        elif field == "avatar":
            avatar_updated = True
        
        if hasattr(current_user, db_field):
            setattr(current_user, db_field, value)
    
    # 同步更新 team_members 表中的头像和昵称
    if avatar_updated or nickname_updated:
        members = db.query(TeamMember).filter(TeamMember.user_id == current_user.id).all()
        for member in members:
            if avatar_updated and 'avatar' in update_data:
                member.avatar = update_data['avatar']
            if nickname_updated and 'nickName' in update_data:
                member.user_name = update_data['nickName']
    
    db.commit()
    db.refresh(current_user)
    
    return ApiResponse(
        data=UserResponse(**current_user.to_dict())
    )


@router.get("/favorites", response_model=ApiResponse[List[str]])
async def get_favorites(
    current_user: User = Depends(get_current_user)
):
    """获取收藏列表"""
    return ApiResponse(
        data=current_user.favorite_venues or []
    )


@router.post("/upload-avatar", response_model=ApiResponse[str])
async def upload_avatar(
    # TODO: 实现文件上传逻辑
    current_user: User = Depends(get_current_user)
):
    """上传头像"""
    # 实际实现需要处理文件上传
    avatar_url = "https://example.com/avatar.jpg"
    return ApiResponse(data=avatar_url)

